import cv2
import pytesseract
from pytesseract import Output
import sys

# 设置pytesseract的路径（如果你在Windows上使用Tesseract-OCR）
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

# 定义鼠标回调函数
def show_coordinates(event, x, y, flags, param):
    if event == cv2.EVENT_MOUSEMOVE:  # 当鼠标移动时
        # 获取当前点的像素值（BGR格式）
        pixel_value = image[y, x]
        b, g, r = pixel_value  # 解包BGR值

        # 更新窗口标题，显示鼠标坐标和像素值
        cv2.setWindowTitle(window_name, f'Image with Rectangles - Coordinates: ({x}, {y}), BGR: ({b}, {g}, {r})')

# 读取图片
image_path = r'd:\tmp\full3.png'
image = cv2.imread(image_path)

# 使用pytesseract获取文本和其位置信息
data = pytesseract.image_to_data(image, output_type=Output.DICT)

# 获取命令行参数（多个目标词组）
target_phrases = sys.argv[1:] if len(sys.argv) > 1 else ["system managed"]

# 遍历所有目标词组
for target_phrase in target_phrases:
    phrase_words = target_phrase.split()  # 将词组拆分为单词列表

    # 遍历OCR结果，查找匹配的词组
    for i in range(len(data['text']) - len(phrase_words) + 1):
        # 检查当前单词和下一个单词是否匹配目标词组
        matched = True
        for j in range(len(phrase_words)):
            if data['text'][i + j].lower() != phrase_words[j].lower():
                matched = False
                break

        if matched:
            # 获取词组的边界框
            x = data['left'][i]
            y = data['top'][i]
            w = data['width'][i + len(phrase_words) - 1] + data['left'][i + len(phrase_words) - 1] - x
            h = max(data['height'][i + j] for j in range(len(phrase_words)))

            # 计算中心点坐标
            center_x = x + w // 2
            center_y = y + h // 2

            print(f"'{target_phrase}' found at center: ({center_x}, {center_y})")

            # 定义截取矩形的宽度和高度
            rect_width = 190
            rect_height = 38

            # 计算矩形的左上角坐标
            rect_x = center_x - rect_width // 2
            rect_y = center_y - rect_height // 2

            # 确保矩形在图像范围内
            rect_x = max(0, rect_x)
            rect_y = max(0, rect_y)
            rect_x_end = min(image.shape[1], rect_x + rect_width)
            rect_y_end = min(image.shape[0], rect_y + rect_height)

            # 在原图上绘制矩形
            cv2.rectangle(image, (rect_x, rect_y), (rect_x_end, rect_y_end), (0, 255, 0), 2)

# 创建窗口并设置鼠标回调函数
window_name = 'Image with Rectangles'
cv2.namedWindow(window_name)
cv2.setMouseCallback(window_name, show_coordinates)

# 显示图片
cv2.imshow(window_name, image)
cv2.waitKey(0)
cv2.destroyAllWindows()